import dayjs from "dayjs";
import utc from 'dayjs/plugin/utc'
import timezone from 'dayjs/plugin/timezone'

dayjs.extend(utc)
dayjs.extend(timezone)

const DEFAULT_FORMAT = 'YYYY-MM-DDTHH:mm:ss.SSS'
const FORMAT1 = 'YYYY-MM-DD HH:mm:ss.SSS'
const FORMAT2 = 'YYYY-MM-DDTHH:mm:ss'

const toUtc = (localTime) => {
    const defRtn = null
    try {
        if (!dayjs(localTime).isValid()) {
            return defRtn
        }
        return dayjs(localTime).utc().format(FORMAT1)
    } catch (e) {
        return defRtn
    }
}

const formatTime = (timeStr) => {
    const defRtn = null
    try {
        timeStr = String(timeStr)
        if (!dayjs(timeStr).isValid()) {
            return defRtn
        }
        const rst = dayjs(timeStr).format(DEFAULT_FORMAT)
        return rst.slice(0, 21);
    } catch (e) {
        return defRtn
    }
}

/**
 * 处理前提：
 *      1 形如：2000-01-01T00:00:00Z 这种，以Z表示UTC时间
 *      2 形如：2000-01-01T00:00:00  这种，不含时区信息，已约定好是UTC时间
 * @param utcStr
 * @returns {string|null}
 *      若验证不通过或解析出错，则返回null
 */
const formatUtc = (utcStr) => {
    const defRtn = null
    try {
        utcStr = String(utcStr);
        let dt = null;
        // const zIdx = utcStr.indexOf('Z');
        // if (zIdx !== -1) {
        //     utcStr = utcStr.slice(0, zIdx)
        // }
        utcStr = utcStr.replace('Z', '')
        if (!dayjs(utcStr).isValid()) {
            return defRtn
        }
        dt = dayjs(utcStr)
        const rst = dt.format(DEFAULT_FORMAT)
        return rst.slice(0, 21) + 'Z';
    } catch (e) {
        return defRtn
    }
}

const getLocalTime = () => {
    return dayjs().format(FORMAT2)
}

const getUtc = () => {
    return dayjs.utc().format(FORMAT2)
}

const getBeiJingTime = () => {
    return dayjs().tz('Asia/Shanghai').format(FORMAT2)
}

const getParisTime = () => {
    return dayjs().tz('Europe/Paris').format(FORMAT2)
}


export {
    toUtc,
    formatTime,
    formatUtc,
    getUtc,
    getBeiJingTime,
    getParisTime
}